import { defineStore } from 'pinia'
import { Session, getToken, setToken } from '@/utils/storage'
import { useMenuApi } from '@/api/menu/index'

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfo = defineStore('userInfo', {
	state: (): UserInfosState => ({
		userInfos: {
			userName: '',
			photo: '',
			roles: [],
			authBtnList: [],
			isAdmin: false,
		},
		token: getToken() as string,
		dictList: {},
	}),
	actions: {
		setToken(token: string) {
			this.token = token
			setToken(token)
		},
		// 个人信息&用户按钮权限获取
		async setUserInfos() {
			const menuApi = useMenuApi()
			const res = await menuApi.getUserInfo()
			const user = res.data
			this.userInfos = {
				userName: user.user.userName,
				photo: user.user.avatar ? import.meta.env.VITE_IMAGE_PREVIEW + user.user.avatar : 'https://img2.baidu.com/it/u=1978192862,2048448374&fm=253&fmt=auto&app=138&f=JPEG?w=504&h=500',
				roles: user.roles,
				authBtnList: user.permissions,
				isAdmin: user.user.admin,
				screenUrl: user.defaultBoardCode,
			}
		},
		// 获取字典信息
		async setDictList() {
			const menuApi = useMenuApi()
			const res = await menuApi.getDictList()
			const dictList = res.data
			this.dictList = dictList
		},
		// 前端模拟获取用户信息
		async setUserInfosFront() {
			// 存储用户信息到浏览器缓存
			if (Session.get('userInfo')) {
				this.userInfos = Session.get('userInfo')
			} else {
				const userInfos = <UserInfos>await this.getApiUserInfo()
				this.userInfos = userInfos
			}
		},
		// 模拟接口数据
		async getApiUserInfo() {
			return new Promise(resolve => {
				setTimeout(() => {
					// 模拟数据，请求接口时，记得删除多余代码及对应依赖的引入
					const userName = 'admin'
					// 模拟数据
					let defaultRoles: Array<string> = []
					let defaultAuthBtnList: Array<string> = []
					// admin 页面权限标识，对应路由 meta.roles，用于控制路由的显示/隐藏
					const adminRoles: Array<string> = ['admin']
					// admin 按钮权限标识
					const adminAuthBtnList: Array<string> = ['btn.add', 'btn.del', 'btn.edit', 'btn.link']
					// test 页面权限标识，对应路由 meta.roles，用于控制路由的显示/隐藏
					const testRoles: Array<string> = ['common']
					// test 按钮权限标识
					const testAuthBtnList: Array<string> = ['btn.add', 'btn.link']
					// 不同用户模拟不同的用户权限
					if (userName === 'admin') {
						defaultRoles = adminRoles
						defaultAuthBtnList = adminAuthBtnList
					} else {
						defaultRoles = testRoles
						defaultAuthBtnList = testAuthBtnList
					}
					// 用户信息模拟数据
					const userInfos = {
						userName: userName,
						photo: userName === 'admin' ? 'https://img2.baidu.com/it/u=1978192862,2048448374&fm=253&fmt=auto&app=138&f=JPEG?w=504&h=500' : 'https://img2.baidu.com/it/u=2370931438,70387529&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
						time: new Date().getTime(),
						roles: defaultRoles,
						authBtnList: defaultAuthBtnList,
					}
					Session.set('userInfo', userInfos)
					resolve(userInfos)
				}, 0)
			})
		},
	},
})
